<template>
	<view
		class="diy-coupon"
		v-show="couponList.length > 0"
		:style="{ 
			background: itemData?.style?.background,
			padding: itemData?.style?.paddingTop + 'px 20rpx'
		}">
		<scroll-view scroll-x="true">
			<view class="swiper swiper-list">
				<couponItem
				:itemData="itemData"
				v-for="(child, index) in couponList"
				:key="index"
				:couponData="child"
				@receive="receiveCoupon"></couponItem>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import { onMounted, ref, watch } from 'vue'
	import couponItem from './coupon-item'
	import useUserStore from '@/store/modules/user'
	import { getMpLogin } from '@/utils/login.js'
	import { couponReceiveList, couponProductReceiveList, couponGetOne } from "@/api/app_api/coupon"
		const userStore = useUserStore()
		const props = defineProps({
			itemData: {
				type: Object,
				default: () => {}
			}
		})
		// 获取优惠券
		const couponList = ref([])
		const getCoupon = () =>{
			if (!userStore.regionCode) return false
			Promise.all([couponReceiveList(), couponProductReceiveList({
				regionCode: userStore.regionCode
			})]).then(([result1, result2]) => {
				const coupon1 = result1.data.map(item => {
					return {...item, couponType: 1}
				}) || []
				const coupon2 = result2.data.map(item => {
					return {...item, couponType: 2}
				}) || []
				const nowTime = new Date()
				const limit = props.itemData?.params?.limit || 5
				couponList.value = coupon1.concat(coupon2).sort((a, b) => a.have - b.have).filter(item => {
					const endTime = new Date(item.endTime)
					return nowTime.getTime() < endTime.getTime()
				}).slice(0, limit)
			})
		}
		
		// 领取优惠券
		const isSubmit = ref(false)
		const receiveCoupon = (e) => {
			if (!getMpLogin()) {
				return false
			}
			if (isSubmit.value) return false
			if (e.have === 0) {
				isSubmit.value = true
				couponGetOne({
					id: e.id,
					productId: e?.productId || ''
				}).then(async res => {
					if (res.code === 200) {
						getCoupon()
						uni.$u.toast('领取成功')
					} else {
						uni.$u.toast(res.msg)
					}
					await uni.$u.sleep(1000)
					isSubmit.value = false
				}).catch(err => {
					isSubmit.value = false
				})
			} else {
				uni.switchTab({
					url: `/pages/category/category`
				})
			}
		}
		onMounted(() => {
			getCoupon()
		})
</script>

<style lang="scss">
.diy-coupon {
	margin-bottom: 20rpx;
	border-radius: 6rpx;
}

.f-s-0 {
	flex-shrink: 0;
}

.diy-coupon .swiper {
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
</style>
